//
//  BRAlertCustomView.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/27.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRAlertCustomView.h"
#import "BRSetSelectListTableViewCell.h"
#import "BRAreaViewController.h"

@interface BRAlertCustomView ()<QMUITableViewDelegate,QMUITableViewDataSource,QMUITextFieldDelegate>
{
    UIView *_shadowView;
    UIView *_contentView;
    QMUILabel *_titleLB;
    NSInteger _type;
    
    //记录选中的下标，
    NSInteger _selectIndex;
    
    UIStackView *_btnStackView;
}

@end

@implementation BRAlertCustomView

- (instancetype)initWithFrame:(CGRect)frame type:(NSInteger)type
{
    self = [super initWithFrame:frame];
    if (self) {
        _type = type;
        _selectIndex = -1;
        [self setUI];
    }
    return self;
}

#pragma mark - ACTION --
- (void)btnClick:(QMUIButton *)btn {
    
    NSInteger tag = btn.tag;
    
    if (tag == 100) {
        // cancel
        [self hidd];
    }else {
        // save
        if (_type == 1) {
            
            if (_selectIndex < 0) return;
            
            [self returnText:@""];
            
            return;
        }
        
        if (_type > 1) {
            
            NSString *areStr = @"";
            if (_type == 2) {
                
                if (self.areaBtn.titleLabel.text.length <= 1) {
                    [BRHud show:Localized(@"toast_requiredCode") inView:self];
                    
                    return;
                }
                if (self.areaBtn.titleLabel.text.length < 4) {
                    [BRHud show:Localized(@"toast_validCode") inView:self];
                    
                    return;
                }
                areStr = [self.areaBtn.titleLabel.text substringFromIndex:1];
                
                if (self.textTF.text.length == 0) {
                    
                    [BRHud show:Localized(@"toast_requiredPhone") inView:self];
                    return;
                }
                if (![BRTools checkPhone:self.textTF.text]) {
                    [BRHud show:Localized(@"toast_validPhone") inView:self];
                    
                    return;
                }
            }
            if (_type == 3) {
                
                if (self.textTF.text.length == 0) {
                    [BRHud show:Localized(@"toast_requiredEmail") inView:self];
                    return;
                }
                if (![BRTools checkEmail:self.textTF.text]) {
                    
                    [BRHud show:Localized(@"toast_validEmail") inView:self];
                    return;
                }
            }
            if (self.otpTF.text.length < 4) {
                [BRHud show:Localized(@"toast_validPhone") inView:self];
                return;
            }
            
            if (self.alertOtpBlock) {
                WS(weakSelf);
                self.alertOtpBlock(areStr, self.textTF.text, self.otpTF.text, ^(BOOL hidden) {
                    if (hidden) {
                        [weakSelf hidd];
                    }
                });
                
            }
            
            return;
        }
        
        [self returnText:self.textTF.text];
        
    }
}

- (void)returnText:(NSString *)text {
    if (self.alertBlock) {
        WS(weakSelf);
        self.alertBlock(text, _selectIndex, ^(BOOL hidden) {
            if (hidden) {
                [weakSelf hidd];
            }
        });
    }
}

- (void)hidd {
    
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)setTitleStr:(NSString *)titleStr {
    _titleStr = titleStr;
    _titleLB.text = titleStr;
}

- (void)setListArr:(NSArray *)listArr {
    _listArr = listArr;
    [self.tableView reloadData];
    WS(weakSelf);
    CGFloat maxH = 52.0 * 5;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        CGFloat contH = weakSelf.tableView.contentSize.height;
        if (contH >= maxH) {
            contH = maxH;
            weakSelf.tableView.scrollEnabled = YES;
        }
        
        [weakSelf.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(contH);
        }];
        [self layoutSubviews];
    });
    
}

- (void)setSelIndex:(NSInteger)selIndex {
    _selectIndex = selIndex;
    _selIndex = selIndex;
}

- (void)getAreaNum {
    
//    BRAreaViewController *vc = [[BRAreaViewController alloc] init];
//
//    [self.jk_navigationController pushViewController:vc animated:YES];
//    WS(weakSelf);
//    vc.selectCodeBlock = ^(NSInteger code) {
//        [weakSelf.areaBtn setTitle:[NSString stringWithFormat:@"+%ld",code] forState:UIControlStateNormal];
//    };
}

- (void)sendOtpClick:(QMUIButton *)btn {
    
    NSString *areStr = @"";
    if (_type == 2) {
        
        if (self.areaBtn.titleLabel.text.length <= 1) {
            [BRHud show:Localized(@"toast_requiredCode") inView:self];
            
            return;
        }
        if (self.areaBtn.titleLabel.text.length < 4) {
            [BRHud show:Localized(@"toast_validCode") inView:self];
            
            return;
        }
        
        areStr = [self.areaBtn.titleLabel.text substringFromIndex:1];
        
        if (self.textTF.text.length == 0) {
            
            [BRHud show:Localized(@"toast_requiredPhone") inView:self];
            return;
        }
        if (![BRTools checkPhone:self.textTF.text]) {
            [BRHud show:Localized(@"toast_validPhone") inView:self];
            
            return;
        }
    }
    if (_type == 3) {
        if (self.textTF.text.length == 0) {
            [BRHud show:Localized(@"toast_requiredEmail") inView:self];
            return;
        }
        if (![BRTools checkEmail:self.textTF.text]) {
            
            [BRHud show:Localized(@"toast_validEmail") inView:self];
            return;
        }
    }
    
    if (self.sendClick) {
        self.sendClick(areStr, self.textTF.text, btn);
    }
}

#pragma mark - textField  Delegate --
- (void)textFieldDidChangeSelection:(UITextField *)textField {
    if (textField == self.otpTF) {
        if (textField.text.length >= 4) {
            [textField resignFirstResponder];
        }
    }
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    NSLog(@"textFieldShouldBeginEditing = %@",textField.text);
    
//    if (textField == self.textTF) {
//        if (textField.text.length >= 25) {
//            return NO;
//        }
//    }
//
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField != self.textTF) {
        return YES;
    }
    if (_type == 2) {
        return [BRTools checkIsNumber:string];
    }
    if (_type == 3) {
        return [BRTools canInputText:string hasEmail:YES];
    }
    return YES;
}

#pragma mark - tableView Delegate --

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.listArr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BRSetSelectListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRSetSelectListTableViewCell"];
    if (!cell) {
        cell = [[BRSetSelectListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BRSetSelectListTableViewCell"];
    }
    cell.index  =  indexPath.row;
    NSString *laStr =  self.listArr[indexPath.row];
    cell.listCell.titleStr = laStr;
    
    [cell.listCell hiddenLine:NO];
    if (indexPath.row + 1 == self.listArr.count) {
        [cell.listCell hiddenLine:YES];
    }
    if (_selectIndex >= 0) {
        cell.listCell.isSelected = _selectIndex == indexPath.row ? YES : NO;
    }else {
        cell.listCell.isSelected = NO;
    }
    
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    _selectIndex = indexPath.row;
    [self.tableView reloadData];
    
}

- (void)selectStr:(NSString *)str {
    
    for (int i = 0; i < self.listArr.count; i++) {
        
        BRSetSelectListTableViewCell *cell = (BRSetSelectListTableViewCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        if ([cell.listCell.titleStr isEqualToString:str]) {
//            cell.selected = YES;
            _selectIndex = i;
            [self.tableView reloadData];
            return;
        }
//        else {
//            cell.selected = NO;
//            cell.listCell.isSelected = NO;
//        }
    }

}

- (void)setRightBtnTitle:(NSString *)title {
    
    QMUIButton *btn = [_btnStackView viewWithTag:101];
    [btn setTitle:title forState:UIControlStateNormal];
}

#pragma mark - SET UI --
- (void)setUI {
    
    UIView *shadow = [[UIView alloc] initWithFrame:self.bounds];
    shadow.backgroundColor = UIColorMakeWithRGBA(0, 0, 0, 0.2);
    [self addSubview:shadow];
    
    
    
    CGFloat  width = ceilf(kScreenWidth - (kMarginLR2 * 2.0));
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = UIColor.qd_backgroundColor2;
    _contentView.layer.cornerRadius = 28;
    _contentView.layer.masksToBounds = YES;
    _contentView.userInteractionEnabled  = YES;
    [self addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(width);
        make.centerX.centerY.equalTo(self);
    }];
    
    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.axis = UILayoutConstraintAxisHorizontal;
    stackView.alignment = UIStackViewAlignmentFill;
    stackView.distribution = UIStackViewDistributionFillEqually;
    _btnStackView = stackView;
    [self addSubview:stackView];
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.bottom.left.right.equalTo(_contentView);
    }];
    for (int i = 0; i < 2; i++) {
        QMUIButton *btn = [[QMUIButton alloc] init];
        [btn setTitleColor:kColorMain forState:UIControlStateNormal];
        NSString *title = i == 0 ? Localized(@"public_cancel") : Localized(@"public_confirm");
        [btn setTitle:title forState:UIControlStateNormal];
        btn.titleLabel.font = i == 0 ? [UIFont fontM:17]:[UIFont fontB:17];
        [stackView addArrangedSubview:btn];
        btn.tag = 100 + i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColor.qd_lineColor2;
    [_contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.left.right.equalTo(_contentView);
        make.top.equalTo(stackView);
    }];
    
    UIView *line2 = [[UIView alloc] init];
    line2.backgroundColor = UIColor.qd_lineColor2;
    [_contentView addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(30);
        make.centerX.centerY.equalTo(stackView);
    }];
    
    
    QMUILabel *titlL = [[QMUILabel alloc] init];
    titlL.textColor = kColorTitle38;
    titlL.font = [UIFont fontB:17];
    titlL.text = @"--";
    titlL.textAlignment = NSTextAlignmentCenter;
    titlL.numberOfLines = 0;
    [_contentView addSubview:titlL];
    [titlL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self->_contentView);
        make.top.equalTo(self->_contentView.mas_top).offset(20);
        make.left.offset(20);
    }];
    _titleLB = titlL;
    
    
    switch (_type) {
        case 0:
        case 2:
        case 3:{
            [self createTextF];
            break;
        }
        case 1:{
            [self creteList];
            break;
        }
        default:
            break;
    }
}

- (void)createTextF {
    
    NSInteger max = 25;
    NSString *placeholder = self.titleStr;
    if (_type == 2) {
        placeholder = Localized(@"Info_phoneNumber");
        max = 15;
    }
    if (_type == 3) {
        placeholder = Localized(@"Info_e-mail");
    }
//    emailTf.clearButtonPositionAdjustment = UIOffsetMake(-20, 0);
//    emailTf.textInsets = UIEdgeInsetsMake(0, 40, 0, 40);
    QMUITextField *textTF = [[QMUITextField alloc] init];
    textTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    textTF.minimumFontSize = 10;
    textTF.adjustsFontSizeToFitWidth = YES;
//    if ([BRThemeManage isHasDark]) {
//        textTF.qmui_clearButtonImage =
//    }
    [textTF br_changeDelegeIcon:[BRThemeManage isHasDark]];
    textTF.clearButtonPositionAdjustment = UIOffsetMake(-12, 0);
    textTF.textInsets = UIEdgeInsetsMake(0, 16, 0, 32);
    textTF.placeholderColor = UIColor.qd_placeholderColor;
    textTF.font  = [UIFont br_fontM:16];
    textTF.textColor =  UIColor.qd_titleTextColor;
    textTF.placeholder = placeholder;
    textTF.tintColor = kColorMain;
    [self addSubview:textTF];
    textTF.layer.cornerRadius = kCorners;
    textTF.backgroundColor = UIColor.qd_tfBackgroundColor3;
    [textTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.left.equalTo(_contentView).offset(kMarginLR);
        make.right.equalTo(_contentView).offset(-kMarginLR);
        make.top.equalTo(_titleLB.mas_bottom).offset(14);
       if(_type == 0) make.bottom.equalTo(_contentView).offset(-68);
    }];
    textTF.delegate = self;
    
    if (_type != 3) {
        textTF.maximumTextLength = max;
    }
    
    self.textTF = textTF;
    if (_type == 0) return;
    if (_type == 2) {
        textTF.keyboardType  = UIKeyboardTypePhonePad;
        textTF.textInsets = UIEdgeInsetsMake(0, 100, 0, 40);

        QMUIButton *areaBtn = [[QMUIButton alloc] qmui_initWithImage:UIImageMake(@"login_ic_more") title:kAddCountryCode];
        areaBtn.imagePosition = QMUIButtonImagePositionRight;
        areaBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 0);
        [areaBtn setTitleColor:UIColor.qd_titleTextColor forState:UIControlStateNormal];
        areaBtn.titleLabel.font = [UIFont br_fontM:16];
        [textTF addSubview:areaBtn];
        [areaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(textTF);
            make.left.equalTo(textTF).offset(0);
            make.height.mas_equalTo(44);
            make.width.mas_equalTo(88);
        }];
        [areaBtn addTarget:self action:@selector(getAreaNum) forControlEvents:UIControlEventTouchUpInside];
        self.areaBtn = areaBtn;
        
//        if ([BrezzeTimeManage share].loginCode.length != 0) {
//            [areaBtn setTitle:[NSString stringWithFormat:@"+%@",[BrezzeTimeManage share].loginCode] forState:UIControlStateNormal];
//        }
    }
    
    QMUITextField *otpTf = [[QMUITextField alloc] init];
    otpTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    otpTf.clearButtonPositionAdjustment = UIOffsetMake(-100, 0);
    otpTf.textInsets = UIEdgeInsetsMake(0, 16, 0, 110);
    otpTf.placeholder = Localized(@"toast_requiredCode");
    otpTf.placeholderColor = UIColor.qd_placeholderColor;
    [otpTf br_changeDelegeIcon:[BRThemeManage isHasDark]];
    otpTf.font = [UIFont br_fontM:16];
    [_contentView addSubview:otpTf];
    otpTf.layer.cornerRadius = kCorners;
    otpTf.backgroundColor = UIColor.qd_tfBackgroundColor3;
    otpTf.tintColor = kColorMain;
    [otpTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.left.equalTo(_contentView).offset(kMarginLR);
        make.right.equalTo(_contentView).offset(-kMarginLR);
        make.top.equalTo(textTF.mas_bottom).offset(16);
        make.bottom.equalTo(_contentView).offset(-68);
    }];
    otpTf.delegate = self;
    otpTf.maximumTextLength = 4;
    otpTf.keyboardType = UIKeyboardTypePhonePad;
    otpTf.adjustsFontSizeToFitWidth = YES;
    otpTf.minimumFontSize = 8;
    
    QMUIButton *otpBtn = [[QMUIButton alloc] init];
    [otpBtn setTitle:Localized(@"login_get") forState:UIControlStateNormal];
    [otpBtn setTitleColor:kColorMain forState:UIControlStateNormal];
    [otpBtn setTitleColor:UIColorMakeWithRGBA(0, 186, 255,1) forState:UIControlStateDisabled];
    [otpBtn setBackgroundColor:UIColor.qd_rentLBBGColor];
    otpBtn.layer.cornerRadius = 5;
    otpBtn.layer.masksToBounds = YES;
    otpBtn.titleLabel.font = [UIFont br_fontM:12];
    [otpTf addSubview:otpBtn];
    [otpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(otpTf);
        make.right.equalTo(otpTf).offset(-8);
        make.height.mas_equalTo(36);
        make.width.mas_equalTo(88);
    }];
    [otpBtn addTarget:self action:@selector(sendOtpClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.otpTF = otpTf;
    self.otpBtn = otpBtn;
    
    
    
}

- (void)creteList {
    
    [self addSubview:self.tableView];
    self.tableView.estimatedRowHeight = 52;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.tableView registerClass:[BRSetSelectListTableViewCell class] forCellReuseIdentifier:@"BRSetSelectListTableViewCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.left.right.equalTo(_contentView);
        make.top.equalTo(_contentView).offset(40);
        make.bottom.equalTo(_contentView).offset(-52);
    }];
    
}

- (QMUITableView *)tableView{
    if (!_tableView) {
        _tableView = [[QMUITableView alloc]initWithFrame:CGRectMake(0,kSafeAreaTopHeight, kScreenWidth, kScreenHeight - kSafeAreaTopHeight) style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}


@end

@interface BRAlertListCell ()
{
    QMUILabel *_titleL;
    UIImageView *_selImg;
    UIView *_line;
}
@end

@implementation BRAlertListCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)setUI {
    
    QMUILabel *titlL = [[QMUILabel alloc] init];
    titlL.textColor = kColorTitle38;
    titlL.font = [UIFont fontM:14];
    titlL.text = @"--";
    [self addSubview:titlL];
    [titlL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self);
        make.left.equalTo(self).offset(14);
    }];
    _titleL = titlL;
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColor.qd_lineColor2;
    [self addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.left.equalTo(self).offset(14);
        make.right.equalTo(self).offset(-14);
        make.bottom.equalTo(self);
    }];
    _line = line;
    
    UIImageView *selI = [[UIImageView alloc] init];
    selI.image = UIImageMake(@"arrow_tick");
    [self addSubview:selI];
    [selI mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(20);
        make.right.equalTo(self).offset(-14);
        make.centerY.equalTo(self);
    }];
    _selImg = selI;
}

- (void)hiddenLine:(BOOL)hidden {
    _line.hidden = hidden;
}
    

- (void)setIsSelected:(BOOL)isSelected {
    _selImg.hidden = !isSelected;
}

- (BOOL)isSelected {
    return !_selImg.isHidden;
}
    
- (NSString *)titleStr {
    return _titleL.text;
}

- (void)setTitleStr:(NSString *)titleStr {
//    _title = title;
    _titleL.text = titleStr;
}
    
   

@end
